package com.businessportal.web.controllers.filebrowser;

import com.businessportal.web.common.FileSystemHelper;
import com.businessportal.web.common.SettingsConfig;
import com.businessportal.web.common.WebServletHelper;
import com.businessportal.web.dataaccess.entities.Login;
import com.businessportal.web.dataaccess.entities.Uploads;
import com.businessportal.web.dataaccess.services.UploadsService;
import com.businessportal.web.dataaccess.services.UserService;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

/**
 * Created by Vadim on 6/25/14.
 */
@WebServlet(urlPatterns = "/securepages/upload.do")
public class FileUploadController extends HttpServlet {

    private static final long MAX_SIZE = 10000000;
    private static final int BUFFER_LENGTH = 4096;

    private static final String FILE_TYPE_PARAM = "fileType";

    public static final String IMAGE_UPLOAD_PAGE_ID = "imageUploadPageId";

    private String ckeditorFuncNum = "";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String fileName = req.getParameter("file");

        File file = new File(SettingsConfig.getInstance().getUploadBaseDir() + File.separator + fileName);

        InputStream input = new FileInputStream(file);

        resp.setContentLength((int) file.length());
        resp.setContentType(new MimetypesFileTypeMap().getContentType(file));

        OutputStream output = resp.getOutputStream();
        byte[] bytes = new byte[BUFFER_LENGTH];
        int read = 0;
        while ((read = input.read(bytes, 0, BUFFER_LENGTH)) != -1) {
            output.write(bytes, 0, read);
            output.flush();
        }

        input.close();
        output.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession(true);

        ServletFileUpload upload = new ServletFileUpload();
        upload.setFileSizeMax(MAX_SIZE);
        upload.setHeaderEncoding("UTF-8");

        String message = null;
        Map<String, String> parameters = new HashMap<String, String>();
        try {
            Login user = (Login)session.getAttribute("user");
            if(null == user){
                throw new Exception("You are not authorized.");
            }


            FileItemIterator iter = upload.getItemIterator(req);
            FileItemStream imageFileItem = null;
            String folder = null;
            InputStream stream = null;
            InputStream filestream = null;
            byte[] fileData = null;

            parameters.put(IMAGE_UPLOAD_PAGE_ID,(String)session.getAttribute(IMAGE_UPLOAD_PAGE_ID));

            if (req.getParameter("CKEditorFuncNum") != null) {
                ckeditorFuncNum = req.getParameter("CKEditorFuncNum");
            }

            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                stream = item.openStream();
                if (item.isFormField()) {
                    parameters.put(item.getFieldName(), Streams.asString(stream, "UTF-8"));
                } else {
                    String currentFileNameExt = FilenameUtils.getExtension(item.getName());
                    String path = FileSystemHelper.prepareFilePath(SettingsConfig.getInstance().getUploadBaseDir(), currentFileNameExt);
                    if(null != path){
                        long size = FileSystemHelper.readToFile(stream, path);

                        String link = WebServletHelper.getUrlBase(req) + "securepages/upload.do?file=" + FilenameUtils.getName(path);

                        Uploads upl = UploadsService.INSTANCE.AddNewUpload("/securepages/upload.do?file=" + FilenameUtils.getName(path), path, user, size);

                        message = "<script type=\"text/javascript\">"
                                + " window.parent.CKEDITOR.tools.callFunction("
                                + ckeditorFuncNum + ",'"
                                + link + "');"
                                + "</script>";

                    } else {
                        new FileUploadException("Couldn't save file");
                    }
                }
            }
        } catch (FileUploadException e) {
            message = e.getMessage();
        } catch (Exception e){
            message = e.getMessage();
        }

        if (isCKeditorUpload(parameters)) {
            resp.setContentType("text/html");
        }
        else {
            resp.setContentType("text/plain");
        }
        resp.setStatus(200);
        resp.getWriter().write(message);
    }

    private boolean isCKeditorUpload(Map<String, String> parameters) {
        return !parameters.containsKey(FILE_TYPE_PARAM) &&
                parameters.containsKey(IMAGE_UPLOAD_PAGE_ID);
    }
}
